<template>
  <div :style="{ width: width, height: height, marginTop: top, marginLeft: left }" class="EchartsChen" :id="container"
    :ref="container">
  </div>
</template>

<script lang="ts">
import { defineComponent, markRaw, nextTick, onMounted, onUnmounted, reactive, toRefs, watch } from 'vue';
import * as charts from "echarts";

export default defineComponent({
  props: {
    options: {
      type: Object,
      require: true
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    animation: {
      type: Boolean,
      default: true
    },
    top: {
      type: String,
      default: "0px"
    },
    left: {
      type: String,
      default: "0px"
    },
    container: {
      type: String,
      default: "container",
      require: true
    },
    isClick: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  setup (props, { emit }) {
    const Aecharts: any = reactive({ value: '' });
    const resize = reactive({ value: 0 });

    onMounted(() => {
      nextTick(() => {
        window.addEventListener('resize', () => {
          resize.value = document.body.offsetWidth;
        });
      });
    });

    onUnmounted(() => { });

    watch(() => props.options, () => {
      changeEcharts(props.options);
    }, {
      deep: true
    });

    watch(() => props.container, (newval) => {
      nextTick(() => {
        let op = reactive({ value: document.getElementById(newval) });
        if (op.value) {
          Aecharts.value = markRaw(charts.init(op.value)); // 初始化图表
        }
        changeEcharts(props.options);
      });
    }, {
      deep: true,
      immediate: true
    });

    watch(() => resize.value, () => {
      Aecharts.value.resize();
    });

    const changeEcharts = (options: any) => {
      if (props.animation) {
        options = {
          ...options,
          animation: true,
          animationDelay: 1000
        };
      }
      options && Aecharts.value.setOption(options, { notMerge: true });
      if (props.isClick) {
        Aecharts.value.on("mouseover", (e: any) => emit('mouseover', e)); // 鼠标移入
        Aecharts.value.on("mouseout", (e: any) => emit('mouseout', e)); // 鼠标移出
        Aecharts.value.on("click", (e: any) => emit('click', e)); // 鼠标点击
      }
    };

    return {
      ...toRefs(Aecharts)
    };

  }
});
</script>
